// pages/daka/daka.js
// 引入SDK核心类
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectedText:'2天内',
    index:0,
    tokenExpires:0,
    token:'',
    showModal: false,
    showModal1: false,
    success: '',
    dakaId:'',
    imgUrl: '',
    formData:{
      clearItemName:'',
      taskProcess:'',
      taskPerson:'',
      taskTime:'',
      actived:'',
      createorName:'',
      photos:[],
      
    },
    projects: ['粉尘作业区域日常清扫', '粉尘仓（干/湿）定期清理', '风管、设备设施内部定期清扫','厂房高处等死角的定期清理'], // 清扫项目列表
    taskProcessed:['未完成','已完成'],
    activeds:['无效','有效'],
    selectedProject: '请选择项目', // 默认选中的项目
    selectedProjectP: '请选择完成情况',
    selectedProjectA: '请选择有效状况',
    currentDateTime: '',
    dataList1:[],
    latitude: 0,
    longitude: 0,
    mapName: "",
    del: true,
    lista: [],
    tpzs:"null",
    sfpz:null,
    dataList: [],
    keyword: '',
    filteredList: [],  // 存储筛选后的列表数据
    // formattedTime: ''
    currentLat:"",
    currentLon:"",
    array:["2天内","4天内","6天内"],
    index:0,
    imags: "",  
    startTime: '开始时间',
    endTime: '结束时间',
    settingTimeType: 'start', // 初始设置开始时间
    dropdownVisible: false, 
    animate: 'myfirst',
    yesorno: 'none',
    flag: true,
    test:'test1',
  	form: {          // 用于其他功能提交的参数
  		ossUrl: []
  	}

  },
  fabiao: function () {
 
    this.setData({
      yesorno: 'block'
    })
 
    this.setData({
      test: 'test1'
    })
 
    this.setData({
      flag: false
    })
 
  },
  laqi: function () {
 
    this.setData({
      test: 'test2',
    })
    this.setData({
      flag: true
    })
  },
  preventTouchMove: function () {
  },
  pickerChange111: function (e) {
    this.setData({
      index: e.detail.value,
      selectedText: this.data.array[e.detail.value]
    });
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal1: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
  },
  xiugai(){
    this.getCurrentDateTime()
    const dateString=this.data.currentDateTime
    const dateObject=new Date(dateString)
    const timestamp=dateObject.getTime()
    this.setData({
      showModal1: true,
      'formData.taskTime':timestamp
    })
    console.log(this.data.currentDateTime)
  },
  bindDateTimeChange: function(e) {
    let date = e.detail.value;
    if (this.data.settingTimeType === 'start') {
      this.setData({
        datetime: date,
        startTime: date,
        settingTimeType: 'end' // 切换到设置结束时间
      });
    } else {
      this.setData({
        datetime: date,
        endTime: date,
        settingTimeType: 'start' // 切换回设置开始时间
      });
    }
  },
  showDeleteModal(id) {
    console.log('要删除的 id 是：', id.currentTarget.dataset.id.id);
    wx.showModal({
      title: '确认删除',
      content: '确定要删除吗？',
      confirmText: '删除',
      confirmColor: '#FF0000',
      success: function(res) {
        if (res.confirm) {
          // 在这里添加删除操作
          wx.request({
            url: 'http://117.81.212.51:5432/api/dustClear/deleteById/'+id.currentTarget.dataset.id.id,
            method:'DELETE',
            header: {
              'Authorization': this.data.BearToken  // 将jwtToken添加到请求头中
            },
            success: (res) => {
              this.getDataList()
              console.log(res.data)
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },
  Change:function(e){
    console.log(e.detail.value);
    this.setData({
      index:e.detail.value
    })
  },
  ok(){
    this.setData({
      dropdownVisible: false
    });
  },
  showDropdown: function() {
    this.setData({
      dropdownVisible: true
    });
  },
  mySelect1: function(e) {
    this.setData({
      tihuoWay: e.currentTarget.dataset.name,
      select: false
    });
  },
  mySelect: function(e) {
    var name = e.currentTarget.dataset.name;
    var now = new Date();
    var start = new Date(now.getTime() - 2 * 60 * 60 * 1000); // 当前时间减去两小时
    var startTime = this.formatTime(start);
    var endTime = this.formatTime(now);
    this.setData({
      tihuoWay: name,
      select: false,
      startTime: startTime,
      endTime: endTime
    })
  },
  formatTime: function(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    return `${this.formatNumber(month)}-${this.formatNumber(day)} ${this.formatNumber(hour)}:${this.formatNumber(minute)}`;
  },
  formatNumber: function(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },
  mySelect(e) {
   var name = e.currentTarget.dataset.name
   this.setData({
    tihuoWay: name,
    select: false
   })
  },
  getCurrentDateTime() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份从 0 开始，需要加 1
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();

    let currentDateTime = year + '-' + this.formatNumber(month) + '-' + this.formatNumber(day) + ' ' + this.formatNumber(hours) + ':' + this.formatNumber(minutes) + ':' + this.formatNumber(seconds);

    this.setData({
      currentDateTime: currentDateTime
    });
  },
  ca(){
    this.setData({
      showModal1: false,
      'formData.clearItemName': '',
      'formData.taskProcess': '',
      'formData.actived': '',
      'formData.createorName': '',
      'formData.taskPerson': '',
      selectedProject:'请选择项目',
      lista: [],
      currentDateTime: '',
      mapName: ''
    });

  },

  formatNumber: function (n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },
  inputDKR: function (e) {
    this.setData({
      'formData.taskPerson': e.detail.value,
      'formData.createorName': e.detail.value
    });
    console.log(this.data.formData)
  },
  submitForm: function () {
    console.log(this.data.formData)
    // 发送数据到后端
    wx.request({
      url: 'http://117.81.212.51:5432/api/dustClear/save',
      header: {
        'Authorization': this.data.BearToken  // 将jwtToken添加到请求头中
      },
      method: 'POST',
      data: this.data.formData,
      success: (res) => {
        console.log(res.data);
      },
      fail: function (error) {
        console.error(error);
      }
    });
    this.setData({
      showModal1: false,
      'formData.location': '',
      'formData.dkrq': '',
      'formData.qsxm': '',
      'formData.dkr': '',
      'formData.sspz': '',
      lista: [],
      currentDateTime: '',
      mapName: ''
    });
    this.getDataList();
  },
  onLoad(){
    qqmapsdk = new QQMapWX({
      key: 'RVCBZ-XLBLZ-2XWXP-7E33J-3C7T6-3HFDA'
    });
  },
  
  sendContent: function () {

  },
  // 选择上传图片的方式
  chooseImageTap() {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍一张'],
      itemColor: "black",
      success(res){
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            // 从相册中选择
            _this.selectPicture()
          } else if (res.tapIndex == 1) {
            // 使用相机
            _this.takePhoto()
          }
        }
      }
    })
  },
  //删除照片
  de(){
    this.del=false;

  },
  selectPicture:function(e){
    wx.chooseMedia({
      count:9,
      mediaType:['image','video'],
      sourceType:"album",
      maxDuration:30,
    success:(res)=>{
      const tempFilePath1 = res.tempFiles[0].tempFilePath;
      console.log(res.tempFiles[0].tempFilePath);
          let i=0;
          var list=new Array
          list.push(res.tempFiles[i].tempFilePath);
      this.setData({
        lista:list,
        // 'formData.sspz': res.tempFiles[0].tempFilePath
      })
      let that = this; // 保存正确的上下文
      wx.uploadFile({
        url: 'http://117.81.212.51:5432/api/image',
        header: {
          'Authorization': this.data.BearToken // 将jwtToken添加到请求头中
        },
        filePath: tempFilePath1,
        method: 'POST',
        name: 'file',
        success: function (res) {
          const imageUrl = JSON.parse(res.data);
          console.log("图片在本机上的路径：" + imageUrl.publicLink);
          let photos = [];
          photos.push('http://117.81.212.51:5432'+imageUrl.publicLink);
          this.setData({
            'formData.photos': photos
          });
          console.log(photos);
        }.bind(this),
        fail: function (error) {
          console.error(error);
        }
      });
      
    }
    })
  },
  //调用相机拍照
  takePhoto(){	
    wx.navigateTo({
      url: '/pages/photo/photo',	//跳转到自定义的一个拍照页面
    })
  },
  // 删除图片
  removeChooseImage(e) {
    let imgs = this.data.form.ossUrl;
    let {index} = e.currentTarget.dataset;
    imgs.splice(index, 1);
    this.setData({
      'form.ossUrl': imgs,
      imageList: imgs
    })
  },
  // 预览图片
  previewBigImage(e) {
    // let imgs = this.data.imageList;
    // let {index} = e.currentTarget.dataset;
    wx.previewImage({
      //当前显示图片
      current: imgs,
      //所有图片
      urls: imgs
    })
  },
  getlocation(){
      // 1.先开始定位
      wx.getLocation({
        type: 'gcj02', // 比较精确
        success: (res) => {
          // 2,地址逆解析  根据经纬度获取实际地址
         qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: (data) => {
              console.log("当前地址信息：", data.result);
              // 存储 详细地址 和当前获取的经纬度
              let address = data.result.address + data.result.formatted_addresses.recommend;
              this.setData({
                currentLoaction: address,
                currentLat: data.result.location.lat,
                currentLon: data.result.location.lng
              })
          
            },
            fail: (error) => {
              console.error("err:", error)
            },
          })
        }
      })
  },
  Cancele(){
    var that = this 
    that.setData({
      sfpz:false
    })

  },
  preventBubble: function(e) {
    // 阻止事件冒泡
    return false;
  },
moveToLocation() {
    let that = this;//防止this指向问题
    wx.chooseLocation({
        success: function (res) {
            // console.log(res.name);
            //赋值给data中的mapName
            that.setData({
                mapName: res.name,
                'formData.dkwz': res.name
            })
        },
        //错误信息
        fail: function () {
            console.log(err);
        }
    })
},
choswq: function(event) {
  const id = event.currentTarget.dataset.id.id;
  console.log(id)
  wx.navigateTo({
    url: '/pages/xiangqin/xiangqin?id=' + id
  });
},
selectChange(e) {
  const selectedProject = e.detail.value;
  console.log("用户选择的清扫项目是：" + selectedProject);
  // 如果需要将选中的项目传递给父组件，可以使用 $emit 方法
  this.$emit('inputXM', selectedProject);
},



error(e){
  console.log(e.detail)
},
onShow: function () {
  this.getDataList(); // 页面显示时获取最新数据
},

getDataList(){
  // 发送请求到后端服务器获取最新数据
  wx.request({
    url: 'http://117.81.212.51:5432/api/dustClear/getAllDustClearrecord?pageSize=10&page=0',
    header: {
      'Authorization': this.data.BearToken  // 将jwtToken添加到请求头中
    },
    success: (res) => {
      this.setData({
        dataList: res.data
      });
      console.log(res.data)
    }
  });
  
},
add(e){
  var that = this 
    that.setData({
      now_state:true
    })
    console.log(that.data.now_state);

},
onInput(e) {
  this.setData({
    keyword: e.detail.value
  });
  this.filterList();
},
enter(){
  wx.navigateTo({
    url: '/pages/xiangqin/xiangqin',
  })
},
onPickerChangeTaskProcess: function (e) {
  const index = e.detail.value;
  this.setData({
    selectedProjectP: this.data.taskProcessed[index],
    'formData.taskProcess':index
  });
  console.log(this.data.formData.taskProcess)
},
onPickerChangeActived: function (e) {
  const index = e.detail.value;
  this.setData({
    selectedProjectA: this.data.activeds[index],
    'formData.actived':index
  });
  console.log(this.data.formData.actived)
},
onPickerChange: function (e) {
  const index = e.detail.value;
  this.setData({
    selectedProject: this.data.projects[index],
    'formData.clearItemName':parseInt(index)+1
  });
  console.log(this.data.formData.clearItemName)
},



filterList() {
  // 根据关键词进行搜索，更新 filteredList
  this.setData({
    filteredList: this.data.dataList.filter(item => {
      return item.dkr.includes(this.data.keyword);
    })
  });
},

/**
 * 生命周期函数--监听页面加载
 */
// onLoad(options) {

// },
onLoad(options) {
  var that=this
  wx.request({
    // ... 其他配置
    url: 'http://117.81.212.51:5432/api/auth/login', // 登录接口
    method: 'POST',
    data: {
      username: '2463610487@qq.com', // 替换为实际的用户名
      password: '123456'  // 替换为实际的密码
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (loginRes) {
      if (loginRes.statusCode === 200) {
        // 使用 'that' 而不是 'this' 来引用正确的上下文
        const token = loginRes.data.token;
        console.log(token);
  
        // 存储 token 并设置过期时间
        that.setData({
          token: 'Bearer ' + token,
          tokenExpires: Date.now() + (loginRes.data.expires_in * 1000)
        });
  
        // 接下来的请求同样使用 'that' 来引用正确的上下文
        wx.request({
          url: 'http://117.81.212.51:5432/api/dustClear/getAllDustClearrecord?pageSize=10&page=0',
          header: {
            'Authorization': that.data.token  // 使用 'that' 而不是 'this'
          },
          success: function (res) {
            // 这里 'this' 指向当前的 wx.request 调用，不是 'onLoad' 函数的上下文
            // 使用 'that' 来引用正确的上下文
            const dataList = res.data.data;
            for (let i = 0; i < dataList.length; i++) {
              // ... 格式化日期时间的代码
            }
            that.setData({
              dataList: dataList
            });
            console.log(that.data.dataList);
          }
        });
      } else {
        console.error('登录失败，状态码：', loginRes.statusCode);
      }
    },
    fail: function (error) {
      // 处理网络请求失败的情况
      console.error('登录请求失败：', error);
    }
  });

},



/**
 * 生命周期函数--监听页面初次渲染完成
 */
onReady() {
},

/**
 * 生命周期函数--监听页面显示
 */
onShow() {


},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide() {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload() {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh() {

},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom() {

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage() {

},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})